//
//  DBselection.m
//  aPlanner
//
//  Created by Daniel Braun on 02/09/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "DBselection.h"


@implementation DBselection

- (void) dealloc {
	[set release];
	[obj release];
	[super dealloc];
}

- (id) initWithObj:(id)n withSet:(NSMutableSet *)aset
{
	self = [super init];
	if (self != nil) {
		obj=[n retain];
		set=[aset retain];
	}
	return self;
}
- (id) valueForUndefinedKey:(NSString *)k;
{
	return [obj valueForKey:k];
}
- (void) setValue:(id)x forUndefinedKey:(NSString *)k;
{
	[obj setValue:x forUndefinedKey:k];
}

- (BOOL) selected
{
	return [set containsObject:obj];
}
- (void) setSelected:(BOOL) k
{
	//if ([self selected] == k) return;
	if (k) [set addObject:obj];
	else [set removeObject:obj];
}

+ (NSMutableArray *) selectionFrom:(NSArray *)a selectionSet:(NSMutableSet *)set 
{
	NSMutableArray *res=[NSMutableArray arrayWithCapacity:[a count]];
	unsigned int i, count = [a count];
	for (i = 0; i < count; i++) {
		NSObject * obj = [a objectAtIndex:i];
		DBselection *d=[[DBselection alloc] initWithObj:obj  withSet:set];
		[res addObject:d];
		[d release];
	}
	return res;
}


@end



@implementation DBHselection

- (void) dealloc {
	[set release];
	[obj release];
	[super dealloc];
}

- (id) initWithObj:(id)n withSet:(NSMutableSet *)aset
{
	self = [super init];
	if (self != nil) {
		obj=[n retain];
		set=[aset retain];
	}
	return self;
}
- (id) valueForUndefinedKey:(NSString *)k;
{
	return [obj valueForKey:k];
}
- (void) setValue:(id)x forUndefinedKey:(NSString *)k;
{
	[obj setValue:x forUndefinedKey:k];
}

- (BOOL) selected
{
	return [set containsObject:obj];
}
- (void) setSelected:(BOOL) k
{
	//if ([self selected] == k) return;
	if (k) [set addObject:obj];
	else [set removeObject:obj];
}

+ (NSMutableArray *) selectionFrom:(NSArray *)a selectionSet:(NSMutableSet *)set 
{
	NSMutableArray *res=[NSMutableArray arrayWithCapacity:[a count]];
	unsigned int i, count = [a count];
	for (i = 0; i < count; i++) {
		HierarchicalObject * obj = [a objectAtIndex:i];
		NSAssert([obj isKindOfClass:[HierarchicalObject class]], @"should be a HierarchicalObject");
		DBHselection *d=[[DBHselection alloc] initWithObj:obj  withSet:set];
		[res addObject:d];
		NSArray *c=[obj children];
		if ([c count]) {
			NSMutableArray *ch;
			ch=[DBHselection selectionFrom:c selectionSet:set];
			[d setChildren:ch];
		}
		[d release];
	}
	return res;
}


@end
